<template>
  <div class="app">
    <!-- <input type="text" v-maxLength="10" v-model="val" />
    <textarea v-model="val2" v-maxLength="30" cols="30" rows="10"></textarea> -->

    <maxLength  type="textarea" maxLen="20" />
  </div>
</template>

<script>
import maxLength from "./views/maxLength";
export default {
  data() {
    return {
      val: "",
      val2: "",
      value: "",
    };
  },
  watch: {
    value(val) {
      console.log(val);
    },
  },
  directives: {
    maxLength: {
      inserted(el, binding) {
        el.setAttribute("maxlength", binding.value);
        let parentWp = el.parentElement;
        let wrap = document.createElement("div");
        let span = document.createElement("span");
        parentWp.replaceChild(wrap, el);
        parentWp.appendChild(wrap);
        wrap.appendChild(el);
        wrap.appendChild(span);

        wrap.className = "wrap";

        if (el.tagName == "TEXTAREA") {
          span.className = "textareaSpan";
        } else if (el.tagName == "INPUT") {
          span.className = "span";
        }

        span.innerHTML = "0/" + binding.value;
      },
      update(el, binding) {
        // el.setAttribute("maxlength", binding.value);
        let valLen = el.value.length;
        let span = el.nextElementSibling;
        span.innerHTML = valLen + "/" + binding.value;

        if (valLen == binding.value) {
          el.style.color = "coral";
        }
      },
    },
  },
  components: {
    maxLength,
  },
};
</script>

<style>
.wrap {
  display: inline-block;
  position: relative;
}

.span {
  position: absolute;
  right: 5px;
  top: 4px;
  font-size: 10px;
  color: #999;
}

.textareaSpan {
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>